package com.zone.module_base

import android.util.Log
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.SpeedCalculator
import com.liulishuo.okdownload.core.Util
import com.liulishuo.okdownload.core.breakpoint.BlockInfo
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo
import com.liulishuo.okdownload.core.cause.EndCause
import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend
import com.zone.core.base.BaseBindingViewModelActivity
import com.zone.core.ext.navigateReplace
import com.zone.module_base.databinding.ActivityTestBinding
import com.zone.module_base.viewmodel.TestActivityVM
import java.io.File

class TestActivity : BaseBindingViewModelActivity<ActivityTestBinding, TestActivityVM>() {
    val TAG = "BaseActivity"
    private val REQUEST_PERMISSION_CODE = 100
    private lateinit var bind: ActivityTestBinding
    private var totalLength: Long = 0
    private var readableTotalLength: String? = null

    override fun inject() {
        BaseApp.appComponent.inject(this)
    }

    override fun initDataBinding(binding: ActivityTestBinding) {
        super.initDataBinding(binding)
        bind = binding
        Log.d(TAG, "initDataBinding: ==============================")

        val url =
            "https://z-cms-test.oss-cn-hangzhou.aliyuncs.com/content/file/2024-06-13/b5aa8ac7c3684dd7a58bc84902b06202.apk"


        // download1(url)
    }

    override fun onEvent(eventId: Int) {
        super.onEvent(eventId)
        when (eventId) {
            0 -> {//无回退栈
                navigateReplace(
                    R.id.test_function_fragment
                )
            }

            1 -> {//下載测试
                navigateReplace(R.id.test_download)
            }

            2 -> {//热修复
                navigateReplace(
                    R.id.test_hot_fix
                )
            }

            3 -> {//图片加载
                navigateReplace(
                    R.id.test_image
                )
            }

            6 -> {//文件操作
                navigateReplace(
                    R.id.test_file
                )
            }

            7 -> {//文件操作
                navigateReplace(
                    R.id.test_web_view
                )
            }

            8 -> {
                navigateReplace(
                    R.id.test_video
                )
            }
        }
    }

    private fun createDownloadFile(): File {
        val downLoadFile = this.cacheDir // 获取app缓存目录，glide就是默认缓存在这儿的
        return File(downLoadFile, "base.apk")
    }

    fun download1(url: String) {
        val apkPath = createDownloadFile()
        if (apkPath.exists()) {
            apkPath.delete()
        }

        var time = 0L

        val task = DownloadTask.Builder(url, File(apkPath.absolutePath))
//            .setFilename(itemInfo.pkgName)//设置下载文件名，没提供的话先看 response header ，再看 url path(即启用下面那项配置)
            .setFilenameFromResponse(false)//是否使用 response header or url path 作为文件名，此时会忽略指定的文件名，默认false
            .setPassIfAlreadyCompleted(true)//如果文件已经下载完成，再次下载时，是否忽略下载，默认为true(忽略)，设为false会从头下载
            .setPreAllocateLength(false) //在获取资源长度后，设置是否需要为文件预分配长度，默认false
            .setMinIntervalMillisCallbackProcess(100) //通知调用者的频率，避免anr，默认3000
            .setWifiRequired(false)//是否只允许wifi下载，默认为false
            .setAutoCallbackToUIThread(true) //是否在主线程通知调用者，默认为true
            .build()
        task.enqueue(object : DownloadListener4WithSpeed() {
            override fun taskStart(task: DownloadTask) {

            }

            override fun connectStart(
                task: DownloadTask,
                blockIndex: Int,
                requestHeaderFields: MutableMap<String, MutableList<String>>
            ) {

            }

            override fun connectEnd(
                task: DownloadTask,
                blockIndex: Int,
                responseCode: Int,
                responseHeaderFields: MutableMap<String, MutableList<String>>
            ) {

            }

            override fun taskEnd(
                task: DownloadTask,
                cause: EndCause,
                realCause: Exception?,
                taskSpeed: SpeedCalculator
            ) {
                Log.d(TAG, "taskEnd: ====================" + task.info?.file?.path)
            }

            override fun infoReady(
                task: DownloadTask,
                info: BreakpointInfo,
                fromBreakpoint: Boolean,
                model: Listener4SpeedAssistExtend.Listener4SpeedModel
            ) {
                totalLength = info.getTotalLength()
                readableTotalLength = Util.humanReadableBytes(totalLength, true)
                Log.i(
                    TAG,
                    ("【2、infoReady】当前进度" + info.getTotalOffset()
                        .toFloat() / totalLength * 100) + "%" + "，" + info.toString()
                )
            }

            override fun progressBlock(
                task: DownloadTask,
                blockIndex: Int,
                currentBlockOffset: Long,
                blockSpeed: SpeedCalculator
            ) {

            }

            override fun progress(
                task: DownloadTask,
                currentOffset: Long,
                taskSpeed: SpeedCalculator
            ) {
                val readableOffset = Util.humanReadableBytes(currentOffset, true)
                val progressStatus = "$readableOffset/$readableTotalLength"
                val speed = taskSpeed.speed()
                val percent = currentOffset.toFloat() / totalLength * 100
                Log.i(
                    TAG,
                    "【6、progress】$currentOffset[$progressStatus]，速度：$speed，进度：$percent%"
                )
            }

            override fun blockEnd(
                task: DownloadTask,
                blockIndex: Int,
                info: BlockInfo?,
                blockSpeed: SpeedCalculator
            ) {

            }
        })
    }
}